package com.example.express_auth2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.Arrays;

/**
 * 在该组件中也可以增加资源服务配置，将该服务模块同时作为资源服务器
 * 授权服务配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private TokenStore tokenStore;


    @Autowired
    DataSource dataSource;
    @Autowired
    private ClientDetailsService cdService;

    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;//授权码服务类型，Services for issuing and storing authorization codes.
    @Autowired
    private AuthenticationManager authenticationManager; //认证管理器,密码授权类型
    @Autowired
    private JwtAccessTokenConverter accessTokenConverter;//jwt令牌服务
    @Autowired
    PasswordEncoder passwordEncoder;

    public AuthorizationServer() {
        super();
    }

    //设置授权码模式的授权码如何存取，没用，使用密码模式
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource){
        return new JdbcAuthorizationCodeServices(dataSource);//设置授权码模式的授权码如何获取
    }

    //将客户端的信息存储到数据库
    @Bean
    public ClientDetailsService clientDetailsService(DataSource dataSource){
        ClientDetailsService clientDetailsService=new JdbcClientDetailsService(dataSource);
        ((JdbcClientDetailsService)clientDetailsService).setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()") ///oauth/token_key:提供共有密钥的端点，如果你使用jwt令牌的话
                .checkTokenAccess("permitAll()") ///oauth/check_token用于资源服务访问的令牌解析端点
                .allowFormAuthenticationForClients();  //允许表单认证
    }


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(cdService);

    }

    //Configure the properties and enhanced functionality of the Authorization Server endpoints.
    //Configure the non-security features of the Authorization Server endpoints,
    // like token store, token customizations, user approvals and grant types.
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)//密码模式需要
                .authorizationCodeServices(authorizationCodeServices)//授权码模式需要
                .tokenServices(tokenServices())//令牌管理服务
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);//允许post请求
    }
    //令牌访问服务
    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices services=new DefaultTokenServices();
        services.setClientDetailsService(cdService);//资源客户端信息服务
        services.setSupportRefreshToken(true);//产生刷新令牌
        services.setTokenStore(tokenStore);//设置令牌储存策略
        //令牌增强
        TokenEnhancerChain tokenEnhancerChain=new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        services.setTokenEnhancer(tokenEnhancerChain);
        services.setAccessTokenValiditySeconds(2592000);//设置令牌有效期30天
        services.setRefreshTokenValiditySeconds(31536000);//设置刷新令牌有效期一年
        return services;
    }
}
